from multiprocessing import Process, Array, Lock, Queue
import time
#进程间通信
#@@共享内存
result = []


class Response:
    status_code =100


def sim_request(x, result):
    response = Response()
    time.sleep(0.5)
    print(f"curent response:{response.status_code}")
    print(f"result id :{id(result)}")
    result.append(response.status_code)



#数组Array方法
array_result = Array("i", 3)


def sim_request1(y, array_result):
    response = Response()
    time.sleep(0.5)
    print(f"使用Array方法的curent response:{response.status_code}")
    print(f"使用Array方法的array_result id :{id(array_result)}")
    array_result[y] = response.status_code


#文件应用+互斥锁的应用
f = open("result.log", "a", encoding="utf-8")


def file_request(z, lock):
    # lock.acquire()
    #上下文管理器，自动管理和释放锁
    with lock:
    # try:
        response = Response()
        time.sleep(0.5)
        print(f"第{z}次使用File方法的curent response:{response.status_code}")
        f.write(f"第{z}次使用File方法的curent response:{response.status_code}\n")
    # except:
    #     pass
    # finally:
    #     lock.release()


#队列Queue方法
queue = Queue(maxsize=50)


def sim_request3(a, queue):
    response = Response()
    time.sleep(0.5)
    print(f"使用Queue方法第{a}次curent response:{response.status_code}")
    queue.put(response.status_code, timeout=1)


if __name__ == "__main__":
    lock = Lock()
    p_arry = []
    for x in range(3):
        p = Process(target=sim_request, args=(x, result))
        p.start()
        p_arry.append(p)

    [p.join() for p in p_arry ]
    print("The process has been end")
    print(result)


    print("以下为数组Array实例")
    p_array1 = []
    for y in range(3):
        p = Process(target=sim_request1, args=(y, array_result))
        p.start()
        p_array1.append(p)
    [p.join() for p in p_array1]
    print("取出数组Array中的数如下：")
    for item in array_result:
        print(item)


    print("以下为File文件的用法")
    p_arry2 = []
    for z in range(10):
        p = Process(target=file_request, args=(z, lock))
        p.start()
        p_arry2.append(p)
    [p.join() for p in p_arry2]
    print("File is OK")


    print("以下为Queue文件的用法")
    p_array3 = []
    for a in range(10):
        p = Process(target=sim_request3, args=(a, queue))
        p.start()
        p_array3.append(p)
    [p.join() for p in p_array3]
    print("队列Queue中的数如下:")
    for i in range(10):
        print(queue.get())
